// import {File as sheetBook, Style} from 'better-xlsx'
// import {saveAs} from 'file-saver'

export class ExportExcel {
  constructor(fileName = 'excel') {
    this.fileName = fileName
    this.sheetQueue = []
  }

  initSheetBook (sheetBook, Style) {
    this.sheetBook = new sheetBook()
    this.Style = Style
  }

  initSheet () {
    this.sheetQueue.forEach(x => this.setSheet(x))
  }

  setSheet ({title, header, data, sheetName}) {
    const sheet = this.sheetBook.addSheet(sheetName)
    if (title) {
      const row = sheet.addRow()
      row.setHeightCM(1)
      const cell = row.addCell()
      cell.value = title
      cell.style.align.v = 'center'
      cell.hMerge = header.length - 1
    }
    // 设置表头
    const headerRow = sheet.addRow()
    headerRow.setHeightCM(1)
    header.forEach(col => {
      const cell = headerRow.addCell()
      const style = new this.Style()
      style.fill.patternType = 'solid'
      style.fill.fgColor = 'faad14'
      style.font.color = '262626'
      cell.style = style
      cell.style.align.v = 'center'
      cell.value = col
    })

    // 设置表内容
    data.forEach(cols => {
      const row = sheet.addRow()
      cols.forEach(col => {
        const cell = row.addCell()
        cell.value = col
      })
    })
    this.autoWidth(sheet, [header, ...data])
  }

  // 自适用宽度, 有点不精准
  autoWidth(ws, data) {
    /*设置worksheet每列的最大宽度*/
    const result = new Array(data[0].length).fill(0)
    const colWidth = data.forEach(row => row.forEach((val, index) => {
      /*先判断是否为null/undefined*/
      let wch = 0
      if (val == null) {
        wch = 10
      } else {
        const v = val.toString()
        const double = v.match(/([\u4e00-\u9fa5]|[\（\）\《\》\——\；\，\。\“\”\<\>\！])/g) // 匹配中文字符
        const doubleLength = double ? double.length : 0 // 中文字符个数
        wch = doubleLength * 2 + (v.length - doubleLength) * 1.1
      }
      result[index] = Math.max(result[index], wch)
    }))
    result.forEach((wch, index) => {
      ws.setColWidth(index, index, wch)
    });
  }

  // 添加 sheet 队列
  addSheet({title, header, data, sheetName = 'sheetName'}) {
    this.sheetQueue.push({title, header, data, sheetName})
    return this
  }

  // 开始下载
  async download() {
    const [{saveAs}, {File:sheetBook, Style}] = await Promise.all([import('file-saver'), import('better-xlsx')])
    this.initSheetBook(sheetBook, Style)
    this.initSheet()
    this.sheetBook.saveAs('blob').then(content => {
      saveAs(content, this.fileName + '.xlsx');
    });
  }
}

export class ExcelData {
  constructor(arr) {
    this._arr = arr
    this.header = []
    this.data = []
    this._list = []
  }

  add(title, attrName, fun) {
    this._list.push([title, attrName, fun])
  }

  getData() {
    this.header = this._list.map(x => x[0])
    this.data = this._arr.map(x => this._list.map(([, attrName, fun]) => {
      const v = x[attrName]
      return fun ? fun(v) : v
    }))
    const {header, data} = this
    return {header, data}
  }
}
